package cc.sjfx.sharedoc.activity.examination;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;

import cn.bmob.v3.AsyncCustomEndpoints;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.CloudCodeListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;
import cn.mandroid.frame.utils.ThreadUtils;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.BasicActivity;
import cc.sjfx.sharedoc.activity.user.UserLoginActivity;
import cc.sjfx.sharedoc.bean.ExamShowListViewBean;
import cc.sjfx.sharedoc.bean.ReplyInfo;
import cc.sjfx.sharedoc.bmob.BmobCache;
import cc.sjfx.sharedoc.bmob.FileInfo4Examination;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.ExamDB;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.function.AsyncImageLoader;
import cc.sjfx.sharedoc.function.AsyncImageLoader.ImageCallback;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cc.sjfx.sharedoc.utils.OpenFileUtils;
import cc.sjfx.sharedoc.widget.adapter.FileAdapter;
import cc.sjfx.sharedoc.widget.adapter.ReplyAdapter;
import cc.sjfx.sharedoc.widget.anotation.ViewInject;
import cc.sjfx.sharedoc.widget.view.ButtonWithNumber;
import cc.sjfx.sharedoc.widget.view.ListViewForScrollView;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class DetailActivity extends BasicActivity implements OnClickListener {
	@ViewInject(id = R.id.scrollView1)
	private ScrollView scrollView;
	@ViewInject(id = R.id.icoImg)
	private ImageView icoImg;
	@ViewInject(id = R.id.nickText)
	private TextView nickText;
	@ViewInject(id = R.id.createTimeText)
	private TextView createTimeText;
	@ViewInject(id = R.id.titleText)
	private TextView titleText;
	@ViewInject(id = R.id.publishLayout)
	private RelativeLayout publishLayout;
	@ViewInject(id = R.id.publishText)
	private TextView publisherText;
	@ViewInject(id = R.id.publishTimeText)
	private TextView publishTimeText;
	@ViewInject(id = R.id.contentText)
	private TextView contentText;
	@ViewInject(id = R.id.downloadLayout)
	private RelativeLayout downloadLayout;
	@ViewInject(id = R.id.downloadUrlText)
	private TextView downloadUrlText;
	@ViewInject(id = R.id.fileListView)
	private ListViewForScrollView filelListView;
	@ViewInject(id = R.id.starImg1)
	private ImageView starImg;
	@ViewInject(id = R.id.button2)
	private ButtonWithNumber replyButton;
	@ViewInject(id = R.id.replyListView)
	private ListViewForScrollView replyListView;
	@ViewInject(id = R.id.replyLayout)
	private LinearLayout replyLayout;
	@ViewInject(id = R.id.replyEdit)
	private EditText replyEdit;
	@ViewInject(id = R.id.submit)
	private Button submit;
	@ViewInject(id = R.id.imgText)
	private TextView imgText;
	InputMethodManager imm;
	private ExamShowListViewBean bean;
	private int type;
	ReplyAdapter replyAdapter = null;
	List<ReplyInfo> replyInfos = new ArrayList<ReplyInfo>();
	String to, toNick;
	boolean iscollect = false;
	PopupWindow galeryWindow;
	View galeryLayout;
	int index = 0;
	List<FileInfo4Examination> list = new ArrayList<FileInfo4Examination>();
	AsyncImageLoader loader;
	ImageView view;
	boolean replyable=true;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);
		initData();

	}

	private void initData() {
		// TODO Auto-generated method stub
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		to = "";
		toNick = "";
		scrollView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub

				switch (arg1.getAction()) {
				case MotionEvent.ACTION_DOWN:
					MLog.i("按下");

					break;
				case MotionEvent.ACTION_MOVE:
					replyLayout.setVisibility(View.GONE);
					try {
						imm.hideSoftInputFromWindow(DetailActivity.this
								.getCurrentFocus().getWindowToken(), 0);
					} catch (Exception e) {
						// TODO: handle exception
						MLog.i("异常");
					}

				default:
					break;
				}

				return false;
			}
		});
		bean = (ExamShowListViewBean) (getIntent().getExtras()
				.getSerializable("info"));
		type = getIntent().getExtras().getInt("type");
		starImg.setOnClickListener(this);
		initCollect();
		initIco();
		initReply();
		titleText.setText(bean.getTitle());
		submit.setOnClickListener(this);
		nickText.setText(bean.getUser().nickName);
		createTimeText.setText(bean.getCreateTime());
		contentText.setText(bean.getContent());
		replyButton.setCount(bean.getReplyNum());
		replyButton.setOnClickListener(this);
		switch (type) {
		case 1:
			setTitle("试题分享");
			if (CheckUtils.isWebSite(bean.getDownloadUrl())) {
				downloadUrlText.setText(Html.fromHtml("<a href='"
						+ bean.getDownloadUrl() + "'><i>"
						+ bean.getDownloadUrl() + "</i></a>"));
				downloadUrlText.setMovementMethod(LinkMovementMethod
						.getInstance());
			} else {
				downloadLayout.setVisibility(View.GONE);
			}
			publisherText.setText(bean.getPublisher());
			publishTimeText.setText(bean.getPublishTime());
			FileAdapter fileAdapter = new FileAdapter(context, bean.getFile());
			filelListView.setAdapter(fileAdapter);
			break;
		case 2:
			setTitle("问答");
			downloadLayout.setVisibility(View.GONE);
			publishLayout.setVisibility(View.GONE);
			if (!CheckUtils.stringIsNull(bean.getFile())) {
				imgText.setVisibility(View.VISIBLE);
				imgText.setOnClickListener(this);
				list = new ArrayList<FileInfo4Examination>();
				try {
					JSONArray jsonArray = new JSONArray(bean.getFile());
					for (int i = 0; i < jsonArray.length(); i++) {
						FileInfo4Examination examination = new FileInfo4Examination();
						examination.setFileNetName(jsonArray.getJSONObject(i)
								.getString("fileNetName"));
						list.add(examination);
					}
					MLog.i(list.size());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		case 3:
			setTitle("拼试卷");
			downloadLayout.setVisibility(View.GONE);
			findViewById(R.id.imageView2).setVisibility(View.GONE);
			publisherText.setVisibility(View.GONE);
			publishTimeText.setText(bean.getPublishTime());
			break;
		default:
			break;
		}

	}

	private void initImgPopupWindow() {
		// TODO Auto-generated method stub
		galeryLayout = getLayoutInflater().inflate(
				R.layout.popupwindow_question_img, null);
		view = (ImageView) galeryLayout.findViewById(R.id.imageView1);
		Button leftButton = (Button) galeryLayout.findViewById(R.id.leftBut);
		Button rightButton = (Button) galeryLayout.findViewById(R.id.rightBut);
		leftButton.setOnClickListener(this);
		rightButton.setOnClickListener(this);
		SetImg();
		galeryWindow = new PopupWindow(galeryLayout,
				android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT, true);
		galeryWindow.setTouchable(true);
		galeryWindow.setTouchInterceptor(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		galeryWindow.setBackgroundDrawable(new BitmapDrawable());
	}

	private void initCollect() {
		// TODO Auto-generated method stub
		if (!UserCache.isLogin
				|| UserCache.user.getCollectList() == null
				|| !UserCache.user.getCollectList()
						.contains(bean.getObjectId())) {
			iscollect = false;
			starImg.setImageResource(R.drawable.star);
		} else {
			iscollect = true;
			starImg.setImageResource(R.drawable.star_collected);
		}
	}

	private void initReply() {
		// TODO Auto-generated method stub
		replyInfos = new ArrayList<ReplyInfo>();
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("objectId", bean.getObjectId());
			jsonObject.put("page", 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
		// 第一个参数是上下文对象，第二个参数是云端代码的方法名称，第三个参数是上传到云端代码的参数列表（JSONObject
		// cloudCodeParams），第四个参数是回调类
		ace.callEndpoint(this, "getReplyContent", jsonObject,
				new CloudCodeListener() {
					@Override
					public void onSuccess(Object object) {
						// TODO Auto-generated method stub
						MLog.i(object);
						JSONObject jsonObject = null;
						int count = 0;
						try {
							jsonObject = new JSONObject((String) object);
							count = jsonObject.getInt("count");
							if (count == 0) {
								TextView emptyView = new TextView(context);
								emptyView.setLayoutParams(new LayoutParams(
										LayoutParams.FILL_PARENT,
										LayoutParams.FILL_PARENT));
								emptyView.setText("暂无回复");
								if (type == 3) {
									int data = bean.getYear() * 1000
											+ bean.getMonth() * 100
											+ bean.getDay();
									Date date = new Date(System
											.currentTimeMillis());
									SimpleDateFormat dateFormat = new SimpleDateFormat(
											"yyyy");
									int year = Integer.parseInt(dateFormat
											.format(date));
									dateFormat = new SimpleDateFormat("MM");
									int month = Integer.parseInt(dateFormat
											.format(date));
									dateFormat = new SimpleDateFormat("dd");
									int day = Integer.parseInt(dateFormat
											.format(date));
									int data1 = year * 1000 + month * 100 + day;
									if (data1 < data) {
										emptyView.setText("考试日期未到，无法回复");
										replyable=false;
									}
								}
								emptyView.setVisibility(View.GONE);
								((ViewGroup) replyListView.getParent())
										.addView(emptyView);
								replyListView.setEmptyView(emptyView);
							} else {
								JSONArray jsonArray = new JSONArray(jsonObject
										.getString("data"));
								for (int i = 0; i < jsonArray.length(); i++) {
									jsonObject = jsonArray.getJSONObject(i);
									ReplyInfo info = new ReplyInfo(jsonObject
											.getString("from"), jsonObject
											.getString("fromNick"), jsonObject
											.getString("to"), jsonObject
											.getString("toNick"), jsonObject
											.getString("replyContent"));
									replyInfos.add(info);
									replyAdapter = new ReplyAdapter(context,
											replyInfos);
									replyListView.setAdapter(replyAdapter);
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						ExamDB.updateReplyNum(context, bean.getObjectId(),
								count);
					}

					@Override
					public void onFailure(int code, String msg) {
						// TODO Auto-generated method stub
						MLog.i(code);
					}
				});
		// for (int i = 0; i <20; i++) {
		// ReplyInfo info=new ReplyInfo("","", "回复"+i);
		// replyInfos.add(info);
		// }
		// replyAdapter=new ReplyAdapter(context, replyInfos);
		// replyListView.setAdapter(replyAdapter);
		replyListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				replyEdit.setHint("回复" + replyInfos.get(arg2).getFromNick());
				replyLayout.setVisibility(View.VISIBLE);
				to = replyInfos.get(arg2).getFrom();
				toNick = replyInfos.get(arg2).getFromNick();

			}
		});
	}

	private void initIco() {
		// TODO Auto-generated method stub
		ThreadUtils.executorService.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (CheckUtils.stringIsNull(bean.getUser().ico)) {
					icoImg.setImageResource(R.drawable.user_defaultico);
				} else {
					File file = new File(BmobPro.getInstance(context)
							.getCacheDownloadDir() + "/" + bean.getUser().ico);
					if (file.exists()) {
						Drawable drawable = Drawable.createFromPath(BmobPro
								.getInstance(context).getCacheDownloadDir()
								+ "/" + bean.getUser().ico);
						icoImg.setImageDrawable(drawable);
					} else {
						BmobProFile.getInstance(context).download(
								bean.getUser().ico, new DownloadListener() {

									@Override
									public void onError(int arg0, String arg1) {
										// TODO Auto-generated method stub

									}

									@Override
									public void onSuccess(String arg0) {
										// TODO Auto-generated method stub
										Drawable drawable = Drawable
												.createFromPath(arg0);
										icoImg.setImageDrawable(drawable);
									}

									@Override
									public void onProgress(String arg0, int arg1) {
										// TODO Auto-generated method stub

									}
								});
					}
				}
			}
		});

	}

	@Override
	public void onBackPressed() {
		if (replyLayout.getVisibility() == View.VISIBLE) {
			replyLayout.setVisibility(View.GONE);
		} else {
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button2:
			replyLayout.setVisibility(View.VISIBLE);
			to = "";
			toNick = "";
			replyEdit.setHint("我来说几句");
			break;
		case R.id.submit:
			MLog.i(replyable);
			if (!replyable) {
				MToast.show(context, "暂时无法回复");
			}else {
				if (UserCache.isLogin) {
					String replyContent = replyEdit.getText().toString();
					if (!CheckUtils.stringIsNull(replyContent)) {
						try {
							sendReply(replyContent);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						MToast.show(context, "回复内容不得为空");
					}
				} else {
					startActivity(null, UserLoginActivity.class);
				}
			}
			break;
		case R.id.starImg1:
			if (UserCache.isLogin) {
				doCollection(iscollect);
			} else {
				startActivity(null, UserLoginActivity.class);
			}
			break;
		case R.id.imgText:
			replyLayout.setVisibility(View.GONE);
			if (galeryWindow == null) {
				initImgPopupWindow();
			}
			galeryWindow.showAtLocation(scrollView, Gravity.CENTER, 0, 0);
			break;
		case R.id.leftBut:
			if (index-- == 0) {
				index = list.size() - 1;
			}
			SetImg();
			break;

		case R.id.rightBut:
			if (++index == list.size()) {
				index = 0;
			}
			SetImg();
			break;
		case R.id.imageView1:
			Intent intent = OpenFileUtils.getIntent(BmobPro
					.getInstance(context).getCacheDownloadDir()
					+ "/"
					+ list.get(index).getFileNetName(), "image");
			startActivity(intent);
			break;
		default:
			break;
		}
	}

	private void SetImg() {
		// TODO Auto-generated method stub
		loader = new AsyncImageLoader(context);
		loader.loadDrawable(list.get(index).getFileNetName(),
				new ImageCallback() {
					@Override
					public void imageLoaded(Bitmap bitmap) {
						// TODO Auto-generated method stub
						view.setImageBitmap(bitmap);
						view.setOnClickListener(DetailActivity.this);
					}
				});
	}

	private void doCollection(final boolean isCollected) {
		// TODO Auto-generated method stub
		List<String> list = UserCache.user.getCollectList();
		if (isCollected) {
			list.remove(bean.getObjectId());
		} else {
			list.add(bean.getObjectId());
		}
		User user = new User();
		user.setCollectList(list);
		user.update(context, UserCache.user.getObjectId(),
				new UpdateListener() {
					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						if (isCollected) {
							MToast.show(context, "已取消");
							iscollect = false;
							starImg.setImageResource(R.drawable.star);
						} else {
							MToast.show(context, "已收藏");
							iscollect = true;
							starImg.setImageResource(R.drawable.star_collected);
						}
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						MToast.show(context, "收藏失败，请稍后再试");
					}
				});
	}

	private void sendReply(String replyContent) throws JSONException {
		// TODO Auto-generated method stub
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("objectId", bean.getObjectId());
		jsonObject.put("from", UserCache.user.getUsername());
		jsonObject.put("fromNick", UserCache.user.getNickName());
		jsonObject.put("to", to);
		jsonObject.put("toNick", toNick);
		jsonObject.put("content", replyContent);
		AsyncCustomEndpoints ace = new AsyncCustomEndpoints();
		// 第一个参数是上下文对象，第二个参数是云端代码的方法名称，第三个参数是上传到云端代码的参数列表（JSONObject
		// cloudCodeParams），第四个参数是回调类
		ace.callEndpoint(this, "doReply", jsonObject, new CloudCodeListener() {

			@Override
			public void onSuccess(Object arg0) {
				// TODO Auto-generated method stub
				if (((String) arg0).equals("success")) {
					MToast.show(context, "回复成功");
					replyLayout.setVisibility(View.GONE);
					replyEdit.setText("");
					initReply();
				} else {
					MToast.show(context, "回复失败，请稍后再试");
				}
			}

			@Override
			public void onFailure(int arg0, String arg1) {
				// TODO Auto-generated method stub
				MToast.show(context, "回复失败，请稍后再试");
			}
		});
	}
}
